package nio;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/09/27
 */
public class NioTest {
    @Test
    public void bufferTest() {
        //申请空间
        IntBuffer buffer = IntBuffer.allocate(10);
        buffer.put(new int[]{1, 2, 3, 4, 5});
        int[] array = buffer.array();
        System.out.println(Arrays.toString(array));
        for (int i = 0; i < 5; i++) {
            System.out.println(buffer.get(i));
        }
        //将指针调回开头
        buffer.flip();

        System.out.println(buffer.get(1));
    }

    /**
     * @param
     * @return 对函数返回值的描述
     * @author 杜伟毅
     * @since 2024/9/28 0028 23:08
     */
    @Test
    public void channelTest() throws IOException {
        //创建一个文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream("a.txt");
        //通过文件输出流得到一个FileChannel
        FileChannel fileChannel = fileOutputStream.getChannel();
        //创建一个buffer并写入数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("hello".getBytes());
        buffer.flip();  //反转，让指针指向数组开头

        //将Buffer中数据写入FileChannel中
        fileChannel.write(buffer);
        fileOutputStream.close();
    }
}
